package com.yyge.config.security.login;

import com.yyge.common.resp.R;
import com.yyge.config.Constants;
import com.yyge.config.security.dto.SecurityUser;
import com.yyge.entity.User;
import com.yyge.mapper.UserMapper;
import com.yyge.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p> 认证成功处理 </p>
 *
 * @author : gityyge
 * @description :
 * @date : 2019/10/12 15:31
 */
@Slf4j
@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        User user = new User();
        SecurityUser securityUser = ((SecurityUser) auth.getPrincipal());
        user.setToken(securityUser.getCurrentUserInfo().getToken());
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(Constants.CURRENT_TOKEN,user.getToken());
        String sessionId = session.getId();
        user.setSessionid(sessionId);
        User userForSeeeion = new User();
        userForSeeeion.setId(securityUser.getCurrentUserInfo().getId());
        userForSeeeion.setToken("");
        userForSeeeion.setSessionid(sessionId);
        userMapper.updateById(userForSeeeion);
        session.setAttribute(Constants.CURRENT_USER, securityUser.getCurrentUserInfo());
        log.info("============onAuthenticationSuccess方法执行，sessionId=" + sessionId);
        log.info("登录成功!");
        ResponseUtils.out(response, R.ok("登录成功!", user));
    }
}
